<template>
    <div class="oral-survey">
        <div class="header">
            <h1>{{ surveyConfig.title }}</h1>
            <p class="subtitle">{{ surveyConfig.subtitle }}</p>
            <div class="header-actions">
                <button @click="goToHome" class="home-btn">
                    <span class="home-icon">🏠</span> {{ surveyConfig.ui.buttons.home }}
                </button>
                <button @click="showSettings = true" class="settings-btn">
                    <span class="settings-icon">⚙️</span> {{ surveyConfig.ui.buttons.settings }}
                </button>
            </div>
        </div>

        <!-- 设置页面 -->
        <div class="settings-modal" v-if="showSettings">
            <div class="settings-content">
                <div class="settings-header">
                    <h2>{{ surveyConfig.settings.title }}</h2>
                    <button @click="closeSettings" class="close-btn">×</button>
                </div>

                <div class="settings-form">
                    <div class="form-group">
                        <label>问答编号：<span class="required">*</span></label>
                        <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的检查）"
                            maxlength="20">
                        <p class="field-hint">编号用于区分不同组的检查，建议使用如：ORAL001、DENTAL_A等格式</p>
                    </div>
                    <div class="form-group">
                        <label>检查医生姓名：<span class="required">*</span></label>
                        <input type="text" v-model="recorderInfo.name" placeholder="请输入检查医生姓名">
                    </div>
                    <div class="form-group">
                        <label>职务/职称：<span class="required">*</span></label>
                        <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或职称（如：主治医师、口腔科医生等）">
                    </div>
                    <div class="form-group">
                        <label>所属机构：</label>
                        <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属医院或机构名称">
                    </div>
                    <div class="form-group">
                        <label>联系方式：</label>
                        <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系电话或邮箱">
                    </div>
                    <div class="form-group">
                        <label>默认备注：</label>
                        <textarea v-model="recorderInfo.defaultRemarks" placeholder="请输入默认备注信息（可选）" rows="3"></textarea>
                    </div>
                </div>

                <div class="settings-actions">
                    <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
                    <button @click="closeSettings" class="cancel-btn">取消</button>
                </div>
            </div>
        </div>

        <!-- 检查医生信息显示 -->
        <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
            <div class="recorder-card">
                <div class="recorder-main-info">
                    <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
                    <p>检查医生：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
                    <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
                </div>
                <div class="recorder-actions">
                    <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
                    <button @click="showExportDialog" class="export-btn">{{ surveyConfig.ui.buttons.export }}</button>
                </div>
            </div>
        </div>

        <!-- 导出数据模态框 -->
        <div class="export-modal" v-if="showExport">
            <div class="export-content">
                <div class="export-header">
                    <h2>{{ surveyConfig.export.title }}</h2>
                    <button @click="closeExport" class="close-btn">×</button>
                </div>

                <div class="export-form">
                    <div class="export-info">
                        <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
                        <p><strong>导出说明：</strong>将从服务器打包当前编号的所有口腔检查数据</p>
                    </div>

                    <div class="form-group">
                        <label>导出密码：<span class="required">*</span></label>
                        <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
                        <p class="field-hint">请联系管理员获取导出密码</p>
                    </div>
                </div>

                <div class="export-actions">
                    <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword">
                        <span v-if="!isExporting">导出压缩包</span>
                        <span v-else>导出中...</span>
                    </button>
                    <button @click="closeExport" class="cancel-btn">取消</button>
                </div>
            </div>
        </div>

        <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
            <!-- 被检查人基本信息 -->
            <div class="section">
                <h2>{{ surveyConfig.sections.basicInfo.title }}</h2>
                <div class="form-group" v-for="field in surveyConfig.sections.basicInfo.fields" :key="field.name">
                    <label>{{ field.label }}：<span v-if="field.required" class="required">*</span></label>
                    <input
                        v-if="field.type === 'text' || field.type === 'number' || field.type === 'tel' || field.type === 'datetime-local'"
                        :type="field.type" v-model="formData[field.name]" :placeholder="field.placeholder"
                        :min="field.min" :max="field.max" :step="field.step">
                    <textarea v-else-if="field.type === 'textarea'" v-model="formData[field.name]"
                        :placeholder="field.placeholder" :rows="field.rows"></textarea>
                    <div v-else-if="field.type === 'radio'" class="radio-group">
                        <label v-for="option in field.options" :key="option.value">
                            <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
                        </label>
                    </div>
                </div>
            </div>

            <!-- 口腔检查项目 -->
            <div class="section">
                <h2>{{ surveyConfig.sections.examination.title }}</h2>
                <p class="examination-description">{{ surveyConfig.sections.examination.description }}</p>

                <!-- 检查项目组 -->
                <div class="exam-groups">
                    <div v-for="group in surveyConfig.examGroups" :key="group.id" class="exam-group-section">
                        <div class="group-header">
                            <h3>{{ group.title }}</h3>
                            <p v-if="group.description" class="group-description">{{ group.description }}</p>
                        </div>

                        <div class="questions">
                            <div v-for="question in group.questions" :key="question.id" class="question-item">
                                <label class="question-label">
                                    {{ question.label }}
                                    <span v-if="question.required" class="required">*</span>
                                </label>
                                <p v-if="question.description" class="question-description">{{ question.description }}
                                </p>

                                <!-- 复合问题 -->
                                <div v-if="question.type === 'composite'" class="composite-question">
                                    <div v-for="subQuestion in question.subQuestions" :key="subQuestion.id"
                                        class="sub-question" :class="{
                                            'conditional': subQuestion.dependsOn,
                                            'hidden': !shouldShowSubQuestion(subQuestion)
                                        }" v-show="shouldShowSubQuestion(subQuestion)">
                                        <label class="sub-question-label">
                                            {{ subQuestion.text }}
                                            <span v-if="subQuestion.required" class="required">*</span>
                                        </label>

                                        <!-- 单选按钮 -->
                                        <div v-if="subQuestion.type === 'radio'" class="radio-group">
                                            <label v-for="option in subQuestion.options" :key="option.value"
                                                class="radio-option">
                                                <input type="radio" :name="subQuestion.id" :value="option.value"
                                                    v-model="formData[subQuestion.field]"
                                                    @change="handleQuestionChange(subQuestion.field)">
                                                <span class="radio-label">{{ option.label }}</span>
                                            </label>
                                        </div>

                                        <!-- 复选框 -->
                                        <div v-else-if="subQuestion.type === 'checkbox'" class="checkbox-group">
                                            <label v-for="option in subQuestion.options" :key="option.value"
                                                class="checkbox-option">
                                                <input type="checkbox" :value="option.value"
                                                    v-model="formData[subQuestion.field]">
                                                <span class="checkbox-label">{{ option.label }}</span>
                                            </label>
                                        </div>

                                        <!-- 下拉选择 -->
                                        <select v-else-if="subQuestion.type === 'select'"
                                            v-model="formData[subQuestion.field]" class="form-select">
                                            <option value="">请选择</option>
                                            <option v-for="option in subQuestion.options" :key="option.value"
                                                :value="option.value">
                                                {{ option.label }}
                                            </option>
                                        </select>

                                        <!-- 数字输入 -->
                                        <div v-else-if="subQuestion.type === 'number'" class="number-input-group">
                                            <input type="number" v-model.number="formData[subQuestion.field]"
                                                :placeholder="subQuestion.placeholder" :min="subQuestion.min"
                                                :max="subQuestion.max" :step="subQuestion.step || 1"
                                                class="form-input number-input">
                                            <span v-if="subQuestion.unit" class="input-unit">{{ subQuestion.unit
                                                }}</span>
                                        </div>

                                        <!-- 文本域 -->
                                        <textarea v-else-if="subQuestion.type === 'textarea'"
                                            v-model="formData[subQuestion.field]" :placeholder="subQuestion.placeholder"
                                            class="form-textarea" :rows="subQuestion.rows || 3"></textarea>

                                        <!-- 文本输入 -->
                                        <input v-else-if="subQuestion.type === 'text'" type="text"
                                            v-model="formData[subQuestion.field]" :placeholder="subQuestion.placeholder"
                                            class="form-input">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 导航按钮 -->
                <div class="form-navigation single-page">
                    <button @click="generateReport" class="nav-btn submit-btn" :disabled="!isFormValid">
                        {{ surveyConfig.ui.buttons.submit }}
                    </button>
                </div>
            </div>
        </div>

        <!-- 结果展示 -->
        <div class="result-section" v-if="showResult">
            <h2>{{ surveyConfig.result.title }}</h2>
            <div class="result-card">
                <div class="result-summary">
                    <h3>{{ result.summary.description }}</h3>
                    <div class="status-indicator" :class="result.summary.overallStatus">
                        <span class="status-text">{{ getStatusText(result.summary.overallStatus) }}</span>
                        <span class="risk-level">风险等级：{{ getRiskLevelText(result.summary.riskLevel) }}</span>
                    </div>
                </div>

                <div class="result-details">
                    <h4>{{ surveyConfig.result.findings }}：</h4>
                    <div class="findings-grid">
                        <div class="finding-item" v-if="result.findings.teeth.caries.present">
                            <h5>龋齿情况</h5>
                            <p>{{ result.findings.teeth.caries.details || '发现龋齿' }}</p>
                            <span class="risk-badge" :class="result.findings.teeth.caries.riskLevel">
                                {{ getRiskLevelText(result.findings.teeth.caries.riskLevel) }}风险
                            </span>
                        </div>

                        <div class="finding-item" v-if="result.findings.teeth.defects.present">
                            <h5>牙齿缺损</h5>
                            <p>{{ result.findings.teeth.defects.details || '发现牙齿缺损' }}</p>
                            <span class="risk-badge" :class="result.findings.teeth.defects.riskLevel">
                                {{ getRiskLevelText(result.findings.teeth.defects.riskLevel) }}风险
                            </span>
                        </div>

                        <div class="finding-item" v-if="result.findings.teeth.missing.present">
                            <h5>牙齿缺失</h5>
                            <p>{{ result.findings.teeth.missing.positions || '发现牙齿缺失' }}</p>
                            <span class="risk-badge" :class="result.findings.teeth.missing.riskLevel">
                                {{ getRiskLevelText(result.findings.teeth.missing.riskLevel) }}风险
                            </span>
                        </div>

                        <div class="finding-item" v-if="result.findings.periodontal.gingival.status !== 'healthy'">
                            <h5>牙龈状况</h5>
                            <p>牙龈{{ result.findings.periodontal.gingival.status === 'gingivitis' ? '炎症' : '异常' }}</p>
                            <span class="risk-badge" :class="result.findings.periodontal.gingival.riskLevel">
                                {{ getRiskLevelText(result.findings.periodontal.gingival.riskLevel) }}风险
                            </span>
                        </div>

                        <div class="finding-item" v-if="!result.findings.periodontal.pockets.normal">
                            <h5>牙周袋</h5>
                            <p>牙周袋深度异常，最大深度：{{ result.findings.periodontal.pockets.maxDepth }}mm</p>
                            <span class="risk-badge" :class="result.findings.periodontal.pockets.riskLevel">
                                {{ getRiskLevelText(result.findings.periodontal.pockets.riskLevel) }}风险
                            </span>
                        </div>

                        <div class="finding-item" v-if="!result.findings.mucosa.normal">
                            <h5>口腔黏膜</h5>
                            <p>{{ result.findings.mucosa.details || '发现黏膜异常' }}</p>
                            <span class="risk-badge" :class="result.findings.mucosa.riskLevel">
                                {{ getRiskLevelText(result.findings.mucosa.riskLevel) }}风险
                            </span>
                        </div>
                    </div>
                </div>

                <div class="result-recommendations" v-if="result.recommendations.length > 0">
                    <h4>{{ surveyConfig.result.recommendations }}：</h4>
                    <ul class="recommendations-list">
                        <li v-for="rec in result.recommendations" :key="rec.title" :class="rec.priority">
                            <div class="rec-header">
                                <span class="rec-category">{{ rec.category }}</span>
                                <span class="rec-priority" :class="rec.priority">{{ getPriorityText(rec.priority)
                                    }}</span>
                            </div>
                            <h5>{{ rec.title }}</h5>
                            <p>{{ rec.content }}</p>
                        </li>
                    </ul>
                </div>

                <div class="result-follow-up">
                    <h4>{{ surveyConfig.result.followUp }}：</h4>
                    <p><strong>建议复查间隔：</strong>{{ result.followUpRecommendations.interval }}</p>
                    <p><strong>复查重要性：</strong>{{ getUrgencyText(result.followUpRecommendations.urgency) }}</p>
                    <div v-if="result.followUpRecommendations.specificAdvice.length > 0">
                        <p><strong>特殊注意事项：</strong></p>
                        <ul>
                            <li v-for="advice in result.followUpRecommendations.specificAdvice" :key="advice">{{ advice
                                }}</li>
                        </ul>
                    </div>
                </div>

                <div class="action-buttons">
                    <button @click="saveToBackendOnly" class="save-btn" :disabled="isSaving">
                        <span v-if="!isSaving">{{ surveyConfig.ui.buttons.save }}</span>
                        <span v-else>保存中...</span>
                    </button>
                    <button @click="resetForm" class="reset-btn">{{ surveyConfig.ui.buttons.restart }}</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { oralConfig } from '@/config/oralConfig.js';
import { calculateOralAssessment } from '@/config/oralLogic.js';

export default {
    name: 'OralSurvey',
    mounted() {
        // 自动设置当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        this.formData.examDate = `${year}-${month}-${day}T${hours}:${minutes}`;

        // 加载检查医生信息
        this.loadRecorderInfo();

        // 初始化表单数据
        this.initializeForm();
    },
    data() {
        return {
            surveyConfig: oralConfig,
            showResult: false,
            showSettings: false,
            showExport: false,
            isExporting: false,
            isSaving: false,
            exportPassword: '',
            // 检查医生信息（设置）
            recorderInfo: {
                surveyId: '',
                name: '',
                position: '',
                institution: '',
                contact: '',
                defaultRemarks: ''
            },
            // 导出选项
            exportOptions: {
                includeRawData: true,
                includeStatistics: true
            },
            // 检查表单数据
            formData: {},
            result: {
                findings: {},
                recommendations: [],
                followUpRecommendations: {},
                summary: {}
            }
        }
    },
    computed: {
        isFormValid() {
            // 个人信息字段已改为选填，不再进行必填验证
            return this.recorderInfo.surveyId &&
                this.recorderInfo.name &&
                this.recorderInfo.position;
        }
    },
    methods: {
        // 导航方法
        goToHome() {
            this.$router.push('/');
        },

        // 初始化表单数据
        initializeForm() {
            // 保留已设置的examDate值
            const existingExamDate = this.formData.examDate;

            this.formData = {
                examDate: existingExamDate || '' // 保留现有的examDate
            };

            // 初始化所有字段为空值或空数组
            this.surveyConfig.examGroups.forEach(group => {
                group.questions.forEach(question => {
                    if (question.type === 'composite') {
                        question.subQuestions.forEach(subQuestion => {
                            if (!Object.prototype.hasOwnProperty.call(this.formData, subQuestion.field)) {
                                if (subQuestion.type === 'checkbox') {
                                    this.formData[subQuestion.field] = [];
                                } else if (subQuestion.type === 'number') {
                                    this.formData[subQuestion.field] = null;
                                } else {
                                    this.formData[subQuestion.field] = '';
                                }
                            }
                        });
                    }
                });
            });
        },

        // 设置相关方法
        saveRecorderInfo() {
            // 验证必填字段
            if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
                alert('请填写所有必填信息（问答编号、检查医生姓名、职务/职称）！');
                return;
            }

            // 保存检查医生信息到本地存储
            localStorage.setItem('oralRecorderInfo', JSON.stringify(this.recorderInfo));
            // 设置默认备注
            if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
                this.formData.remarks = this.recorderInfo.defaultRemarks;
            }
            this.showSettings = false;
            alert('检查医生信息已保存！');
        },

        closeSettings() {
            this.showSettings = false;
        },

        loadRecorderInfo() {
            // 从本地存储加载检查医生信息
            const saved = localStorage.getItem('oralRecorderInfo');
            if (saved) {
                this.recorderInfo = JSON.parse(saved);
                // 设置默认备注
                if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
                    this.formData.remarks = this.recorderInfo.defaultRemarks;
                }
            }
        },

        // 导出相关方法
        showExportDialog() {
            this.showExport = true;
            this.exportPassword = '';
        },

        closeExport() {
            this.showExport = false;
            this.exportPassword = '';
            this.isExporting = false;
        },

        async exportData() {
            this.isExporting = true;

            try {
                // 发送导出请求到服务器
                const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/export-oral-survey`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        surveyId: this.recorderInfo.surveyId,
                        password: this.exportPassword,
                        exportOptions: this.exportOptions
                    })
                });

                if (response.status === 401) {
                    alert('密码错误，请重新输入！');
                    return;
                }

                if (!response.ok) {
                    throw new Error('导出请求失败');
                }

                // 获取服务器返回的压缩包
                const blob = await response.blob();

                if (blob.size === 0) {
                    alert('当前问答编号下没有口腔检查数据！');
                    return;
                }

                // 下载服务器生成的压缩包
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `口腔检查数据_${this.recorderInfo.surveyId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.zip`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);

                alert('数据导出成功！');
                this.closeExport();
            } catch (error) {
                console.error('导出失败:', error);
                alert('导出失败，请检查网络连接或联系管理员！');
            } finally {
                this.isExporting = false;
            }
        },

        // 表单导航方法
        shouldShowSubQuestion(subQuestion) {
            if (!subQuestion.dependsOn) return true;

            const dependentValue = this.formData[subQuestion.dependsOn];
            if (subQuestion.showWhen) {
                return subQuestion.showWhen.includes(dependentValue);
            }

            // 如果有依赖但没有showWhen，则当依赖字段有值时显示
            return dependentValue !== '' && dependentValue !== null && dependentValue !== undefined;
        },

        handleQuestionChange(fieldName) {
            // 当问题答案改变时，清除相关的条件性问题
            this.surveyConfig.examGroups.forEach(group => {
                group.questions.forEach(question => {
                    if (question.type === 'composite') {
                        question.subQuestions.forEach(subQuestion => {
                            if (subQuestion.dependsOn === fieldName && !this.shouldShowSubQuestion(subQuestion)) {
                                if (subQuestion.type === 'checkbox') {
                                    this.formData[subQuestion.field] = [];
                                } else if (subQuestion.type === 'number') {
                                    this.formData[subQuestion.field] = null;
                                } else {
                                    this.formData[subQuestion.field] = '';
                                }
                            }
                        });
                    }
                });
            });
        },

        generateReport() {
            // 使用口腔检查评估逻辑
            this.result = calculateOralAssessment(this.formData);
            this.showResult = true;
        },

        async saveToBackendOnly() {
            this.isSaving = true;

            try {
                // 1. 保存检查数据到后台
                await this.saveToBackend();

                // 2. 生成检查报告内容
                const timestamp = new Date().toLocaleString('zh-CN');
                const examTime = this.formData.examDate ?
                    new Date(this.formData.examDate).toLocaleString('zh-CN') :
                    timestamp;

                const content = `口腔检查结果报告
问答编号：${this.recorderInfo.surveyId}
生成时间：${timestamp}

=== 检查医生信息 ===
检查医生：${this.recorderInfo.name}
职务/职称：${this.recorderInfo.position}
所属机构：${this.recorderInfo.institution}
联系方式：${this.recorderInfo.contact}
检查时间：${examTime}
备注：${this.formData.remarks || '无'}

=== 被检查人基本信息 ===
姓名：${this.formData.patientName}
年龄：${this.formData.age}岁
性别：${this.formData.gender === 'male' ? '男性' : '女性'}
病历号/身份证号：${this.formData.patientId || '未填写'}
籍贯：${this.formData.birthplace || '未填写'}
联系电话：${this.formData.phone || '未填写'}

=== 检查结果总结 ===
总体状况：${this.getStatusText(this.result.summary.overallStatus)}
风险等级：${this.getRiskLevelText(this.result.summary.riskLevel)}
检查总结：${this.result.summary.description}

=== 详细检查发现 ===
${this.generateFindingsText()}

=== 治疗建议 ===
${this.result.recommendations.map((rec, index) =>
                    `${index + 1}. 【${rec.category}】${rec.title}
   优先级：${this.getPriorityText(rec.priority)}
   建议：${rec.content}`
                ).join('\n\n')}

=== 复查建议 ===
建议复查间隔：${this.result.followUpRecommendations.interval}
复查重要性：${this.getUrgencyText(this.result.followUpRecommendations.urgency)}
${this.result.followUpRecommendations.specificAdvice.length > 0 ?
                        '特殊注意事项：\n' + this.result.followUpRecommendations.specificAdvice.map(advice => `• ${advice}`).join('\n') :
                        ''}

报告结束
`;

                // 3. 保存检查报告到@data/文件夹
                await this.saveFileToDataFolder(content);

                alert('✅ 数据已成功保存到后台！\n\n📁 检查数据：survey_data/\n📄 检查报告：@data/');

            } catch (error) {
                console.error('保存到后台失败:', error);
                alert('❌ 保存失败，请检查网络连接或联系管理员！\n\n错误信息：' + error.message);
            } finally {
                this.isSaving = false;
            }
        },

        async saveToBackend() {
            // 构建符合OralSurveyData模型的数据格式
            const surveyData = {
                surveyId: this.recorderInfo.surveyId,
                examDate: new Date().toISOString(),
                examinerName: this.recorderInfo.name,
                examinerPosition: this.recorderInfo.position,
                examinerInstitution: this.recorderInfo.institution,
                examinerContact: this.recorderInfo.contact,
                patientName: this.formData.patientName || "未填写",
                age: this.formData.age || 0,
                gender: this.formData.gender,
                patientId: this.formData.patientId,
                birthplace: this.formData.birthplace,
                phone: this.formData.phone,
                remarks: this.formData.remarks,

                // 检查结果字段
                cariesPresent: this.formData.caries_present === 'yes',
                cariesDetails: this.formData.caries_details,
                cariesSeverity: Array.isArray(this.formData.caries_severity) ?
                    this.formData.caries_severity.join(',') : this.formData.caries_severity,

                defectPresent: this.formData.defect_present === 'yes',
                defectCause: Array.isArray(this.formData.defect_cause) ?
                    this.formData.defect_cause.join(',') : this.formData.defect_cause,
                defectDetails: this.formData.defect_details,

                missingPresent: this.formData.missing_present === 'yes',
                missingPositions: this.formData.missing_positions,
                missingDuration: this.formData.missing_duration,

                gingivalColor: this.formData.gingival_color,
                gingivalTexture: this.formData.gingival_texture,
                gingivalBleeding: this.formData.gingival_bleeding,
                gingivalAbnormalDesc: this.formData.gingival_abnormal_desc,

                pocketDepthNormal: this.formData.pocket_depth_normal === 'normal',
                pocketDepthDetails: this.formData.pocket_depth_details,
                pocketDepthMax: this.formData.pocket_depth_max,

                boneResorption: this.formData.bone_resorption,
                boneResorptionSites: this.formData.bone_resorption_sites,

                mucosaNormal: this.formData.mucosa_normal === 'normal',
                mucosaLesionType: Array.isArray(this.formData.mucosa_lesion_type) ?
                    this.formData.mucosa_lesion_type.join(',') : this.formData.mucosa_lesion_type,
                mucosaLesionDetails: this.formData.mucosa_lesion_details,

                facialSymmetryNormal: this.formData.facial_symmetry_normal === 'normal',
                asymmetryDescription: this.formData.asymmetry_description,

                tmjClicking: this.formData.tmj_clicking,
                tmjPain: this.formData.tmj_pain,
                mouthOpening: this.formData.mouth_opening,
                tmjOtherSymptoms: this.formData.tmj_other_symptoms,

                // 评估结果
                overallStatus: this.result.summary.overallStatus,
                riskLevel: this.result.summary.riskLevel,
                summary: this.result.summary.description,

                createdAt: new Date().toISOString()
            };

            const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-oral-survey`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(surveyData)
            });

            if (!response.ok) {
                throw new Error('保存检查数据失败');
            }
        },

        async saveFileToDataFolder(content) {
            // 通过API保存文件到@data/文件夹
            const filename = `口腔检查结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

            const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    filename: filename,
                    content: content,
                    surveyId: this.recorderInfo.surveyId
                })
            });

            if (!response.ok) {
                throw new Error('保存检查报告失败');
            }
        },

        resetForm() {
            this.formData = {};
            this.result = {
                findings: {},
                recommendations: [],
                followUpRecommendations: {},
                summary: {}
            };
            this.showResult = false;
            this.initializeForm();
        },

        // 辅助方法
        getStatusText(status) {
            const statusMap = {
                excellent: '优秀',
                good: '良好',
                fair: '一般',
                poor: '较差'
            };
            return statusMap[status] || '未知';
        },

        getRiskLevelText(level) {
            const levelMap = {
                low: '低',
                medium: '中',
                high: '高'
            };
            return levelMap[level] || '未知';
        },

        getPriorityText(priority) {
            const priorityMap = {
                urgent: '紧急',
                high: '高',
                medium: '中',
                low: '低'
            };
            return priorityMap[priority] || '未知';
        },

        getUrgencyText(urgency) {
            const urgencyMap = {
                urgent: '紧急',
                important: '重要',
                routine: '常规'
            };
            return urgencyMap[urgency] || '常规';
        },

        generateFindingsText() {
            const findings = [];

            if (this.result.findings.teeth.caries.present) {
                findings.push(`龋齿：${this.result.findings.teeth.caries.details || '发现龋齿'}`);
            }

            if (this.result.findings.teeth.defects.present) {
                findings.push(`牙齿缺损：${this.result.findings.teeth.defects.details || '发现牙齿缺损'}`);
            }

            if (this.result.findings.teeth.missing.present) {
                findings.push(`牙齿缺失：${this.result.findings.teeth.missing.positions || '发现牙齿缺失'}`);
            }

            if (this.result.findings.periodontal.gingival.status !== 'healthy') {
                findings.push(`牙龈状况：${this.result.findings.periodontal.gingival.status === 'gingivitis' ? '炎症' : '异常'}`);
            }

            if (!this.result.findings.periodontal.pockets.normal) {
                findings.push(`牙周袋：深度异常，最大${this.result.findings.periodontal.pockets.maxDepth}mm`);
            }

            if (!this.result.findings.mucosa.normal) {
                findings.push(`口腔黏膜：${this.result.findings.mucosa.details || '发现异常'}`);
            }

            return findings.length > 0 ? findings.join('\n') : '未发现明显异常';
        }
    }
}
</script>

<style scoped>
.oral-survey {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
    color: white;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.header h1 {
    margin: 0 0 10px 0;
    font-size: 2.5em;
    font-weight: 300;
}

.subtitle {
    margin: 0 0 20px 0;
    font-size: 1.2em;
    opacity: 0.9;
}

.header-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
}

.home-btn,
.settings-btn {
    padding: 10px 20px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    background: rgba(255, 255, 255, 0.1);
    color: white;
    border-radius: 25px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 8px;
}

.home-btn:hover,
.settings-btn:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
    transform: translateY(-2px);
}

/* 设置模态框样式 */
.settings-modal,
.export-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.settings-content,
.export-content {
    background: white;
    padding: 30px;
    border-radius: 15px;
    width: 90%;
    max-width: 600px;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.settings-header,
.export-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #f0f0f0;
}

.close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #999;
    padding: 5px;
    border-radius: 50%;
    width: 35px;
    height: 35px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.close-btn:hover {
    background: #f0f0f0;
    color: #333;
}

/* 检查医生信息显示 */
.recorder-info-display {
    margin-bottom: 30px;
}

.recorder-card {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-left: 4px solid #4CAF50;
}

.recorder-main-info h3 {
    margin: 0 0 5px 0;
    color: #333;
}

.recorder-main-info p {
    margin: 5px 0;
    color: #666;
}

.recorder-actions {
    display: flex;
    gap: 10px;
}

.edit-recorder-btn,
.export-btn {
    padding: 8px 16px;
    border: 1px solid #ddd;
    background: white;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.edit-recorder-btn:hover {
    background: #f0f0f0;
}

.export-btn {
    background: #28a745;
    color: white;
    border-color: #28a745;
}

.export-btn:hover {
    background: #218838;
}

/* 表单样式 */
.section {
    background: white;
    padding: 30px;
    margin-bottom: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.section h2 {
    margin: 0 0 20px 0;
    color: #333;
    font-size: 1.8em;
    border-bottom: 2px solid #4CAF50;
    padding-bottom: 10px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
}

.required {
    color: #dc3545;
}

.form-group input,
.form-group textarea,
.form-select {
    width: 100%;
    padding: 12px;
    border: 2px solid #e1e5e9;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus,
.form-select:focus {
    outline: none;
    border-color: #4CAF50;
    box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}

.field-hint {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}

.radio-group,
.checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.radio-option,
.checkbox-option {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px;
    border: 2px solid #e1e5e9;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.radio-option:hover,
.checkbox-option:hover {
    border-color: #4CAF50;
    background: #f8fff8;
}

.radio-option input[type="radio"],
.checkbox-option input[type="checkbox"] {
    width: auto;
}

/* 检查项目组样式 */
.exam-group-section {
    margin-bottom: 30px;
}

.group-header h3 {
    color: #4CAF50;
    margin-bottom: 10px;
}

.group-description {
    color: #666;
    font-style: italic;
    margin-bottom: 20px;
}

.question-item {
    margin-bottom: 25px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #4CAF50;
}

.question-label {
    font-weight: 500;
    margin-bottom: 10px;
    display: block;
}

.question-description {
    color: #666;
    font-size: 14px;
    margin-bottom: 15px;
}

.composite-question {
    margin-top: 15px;
}

.sub-question {
    margin-bottom: 20px;
    padding: 15px;
    background: white;
    border-radius: 6px;
    border: 1px solid #e1e5e9;
}

.sub-question-label {
    font-weight: 500;
    margin-bottom: 10px;
    display: block;
    color: #333;
}

.number-input-group {
    display: flex;
    align-items: center;
    gap: 10px;
}

.input-unit {
    color: #666;
    font-size: 14px;
}

.form-navigation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 10px;
}

.form-navigation.single-page {
    justify-content: center;
}

.nav-btn {
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    transition: all 0.3s ease;
}

.prev-btn {
    background: #6c757d;
    color: white;
}

.prev-btn:hover {
    background: #5a6268;
}

.next-btn,
.submit-btn {
    background: #4CAF50;
    color: white;
}

.next-btn:hover,
.submit-btn:hover {
    background: #45a049;
}

.submit-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.progress-indicator {
    text-align: center;
}

.progress-bar {
    width: 200px;
    height: 8px;
    background: #e1e5e9;
    border-radius: 4px;
    margin-top: 5px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: #4CAF50;
    transition: width 0.3s ease;
}

/* 结果展示样式 */
.result-section {
    background: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.result-card {
    background: #f8f9fa;
    padding: 25px;
    border-radius: 10px;
    border-left: 4px solid #4CAF50;
}

.result-summary {
    text-align: center;
    margin-bottom: 25px;
}

.result-summary h3 {
    color: #4CAF50;
    margin-bottom: 15px;
    font-size: 1.5em;
}

.status-indicator {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 10px;
}

.status-indicator.excellent {
    color: #28a745;
}

.status-indicator.good {
    color: #4CAF50;
}

.status-indicator.fair {
    color: #ffc107;
}

.status-indicator.poor {
    color: #dc3545;
}

.findings-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 15px;
    margin-top: 15px;
}

.finding-item {
    background: white;
    padding: 15px;
    border-radius: 8px;
    border-left: 4px solid #4CAF50;
}

.finding-item h5 {
    margin: 0 0 8px 0;
    color: #333;
}

.finding-item p {
    margin: 0 0 10px 0;
    color: #666;
}

.risk-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
}

.risk-badge.low {
    background: #d4edda;
    color: #155724;
}

.risk-badge.medium {
    background: #fff3cd;
    color: #856404;
}

.risk-badge.high {
    background: #f8d7da;
    color: #721c24;
}

.recommendations-list {
    list-style: none;
    padding: 0;
}

.recommendations-list li {
    margin-bottom: 15px;
    padding: 15px;
    background: white;
    border-radius: 8px;
    border-left: 4px solid #4CAF50;
}

.recommendations-list li.urgent {
    border-left-color: #dc3545;
}

.recommendations-list li.high {
    border-left-color: #fd7e14;
}

.recommendations-list li.medium {
    border-left-color: #ffc107;
}

.rec-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.rec-category {
    background: #e9ecef;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    color: #495057;
}

.rec-priority {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
}

.rec-priority.urgent {
    background: #f8d7da;
    color: #721c24;
}

.rec-priority.high {
    background: #ffeaa7;
    color: #856404;
}

.rec-priority.medium {
    background: #fff3cd;
    color: #856404;
}

.rec-priority.low {
    background: #d1ecf1;
    color: #0c5460;
}

.action-buttons {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-top: 25px;
}

.save-btn,
.reset-btn {
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    transition: all 0.3s ease;
}

.save-btn {
    background: #28a745;
    color: white;
}

.save-btn:hover {
    background: #218838;
}

.save-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.reset-btn {
    background: #6c757d;
    color: white;
}

.reset-btn:hover {
    background: #5a6268;
}

/* 设置和导出按钮样式 */
.settings-actions,
.export-actions {
    display: flex;
    gap: 15px;
    justify-content: flex-end;
    margin-top: 25px;
}

.save-settings-btn,
.export-confirm-btn {
    background: #4CAF50;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.save-settings-btn:hover,
.export-confirm-btn:hover {
    background: #45a049;
}

.export-confirm-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.cancel-btn {
    background: #6c757d;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.cancel-btn:hover {
    background: #5a6268;
}

.export-info {
    background: #e7f3ff;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    border-left: 4px solid #007bff;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .oral-survey {
        padding: 10px;
    }

    .header h1 {
        font-size: 2em;
    }

    .header-actions {
        flex-direction: column;
        gap: 10px;
    }

    .settings-content,
    .export-content {
        width: 95%;
        padding: 20px;
    }

    .recorder-card {
        flex-direction: column;
        gap: 15px;
        text-align: center;
    }

    .form-navigation {
        flex-direction: column;
        gap: 15px;
    }

    .progress-indicator {
        order: -1;
    }

    .action-buttons {
        flex-direction: column;
    }

    .findings-grid {
        grid-template-columns: 1fr;
    }
}
</style>
